var fs = require("fs");
var AIAnalyzeData = require('../model/AIAnalyzeData').AIAnalyzeData;

var csvPath = "../camera.csv";
class AIAnalyzeCSVReader {
    static readCSVAsyn() {
        return new Promise((resolve, reject) => {
            fs.readFile(csvPath, function (err, data) {
                if (err) {
                    reject(err);
                    return;
                }
                data = data.toString();
                let rows = new Array();
                rows = data.split("\r\n");
                resolve(rows);
            });
        });
    }

    static setCSVPath(path) {
        csvPath = path;
    }

    static readCSV() {
        let data = fs.readFileSync(csvPath);
        if (null == data) {
            return null;
        }

        let analyzes = new Map();
        data = data.toString();
        let rows = new Array();
        rows = data.split("\r\n");

        for (var i = 1; i < rows.length; i++) {
            let analyze = AIAnalyzeCSVReader._createAnalyze(rows[i]);
            console.error(JSON.stringify(analyze));
            analyzes.set(analyze.cameraId, analyze);
        }
        return analyzes;
    }

    static _createAnalyze(row) {
        let arr = row.split(',');
        if (arr.length < 3) {
            return null;
        }
        let analyze = new AIAnalyzeData();
        analyze.cameraId = arr[0];
        analyze.cameraIP = arr[1];
        analyze.uri  = arr[2];

        if (arr.length > 4) {
            analyze.extends = arr[3];
        }
        if (arr.length > 5) {
            analyze.remark = arr[4];
        }
        if (arr.length > 6) {
            analyze.type = arr[5];
        }
        return analyze;
    }
}

module.exports = AIAnalyzeCSVReader;
